package com.listview;

import java.io.*;
import java.util.*;

import org.json.*;

import android.app.*;
import android.content.*;
import android.os.*;
import android.support.v4.app.ListFragment;
import android.util.*;
import android.view.*;
import android.widget.*;

import com.facebook.*;
import com.facebook.model.*;
import com.formen.ndk.*;

public class SnsListView extends ListFragment {

	static String[] MOBILE_OS = null;
	ProgressDialog pBar;
	private static final List<String> PERMISSIONS = Arrays
			.asList("publish_actions");
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private boolean pendingPublishReauthorization = false;

	private Session.StatusCallback statusCallback = new SessionStatusCallback();
	Session session;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// setListAdapter(new ArrayAdapter<String>(this, R.layout.list_mobile,
		// R.id.label, MOBILE_OS));
		pBar = ProgressDialog.show(getActivity(), "", "잠시만 기다려주세요.");
		BackThread backt1 = new BackThread();
		backt1.setDaemon(true);
		backt1.start();
		/** Facebook */
		// start Facebook Login
		session = Session.getActiveSession();

	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		if (position == 0)
			Toast.makeText(getActivity(), "타이틀 바 외 목록을 누르세요",
					Toast.LENGTH_SHORT).show();
		else {
			// get selected items
			String selectedValue = (String) getListAdapter().getItem(position);
			String[] split = selectedValue.split("\t");
			Toast.makeText(
					getActivity(),
					"이름 : " + split[1] + "\n만난 시간 : " + split[5] + "\n만난 장소 : "
							+ split[6], Toast.LENGTH_SHORT).show();

			// 이름, 만난시간 및 장소, 코멘트, 링크, 그림

			DialogFeed(split[0], split[1], split[5], split[6]);
		}
	}

	private void DialogFeed(final String id, final String name,
			final String mTime, final String mLoca) {
		
		Intent i = new Intent(getActivity(), FaceBookTest.class);
		i.putExtra("Id", id);
		i.putExtra("Name", name);
		i.putExtra("mTime", mTime);
		i.putExtra("mLoca", mLoca);
		startActivity(i);

//		AlertDialog.Builder aDialog = new AlertDialog.Builder(FaceBookTest.this);
//		aDialog.setTitle("담벼락에 게시");
//		aDialog.setIcon(R.drawable.facebook_ico);
//		aDialog.setView(layout);
//
//		aDialog.setPositiveButton("올리기", new DialogInterface.OnClickListener() {
//			public void onClick(DialogInterface dialog, int which) {
//				EditText cmtEdt = (EditText) layout.findViewById(R.id.comment);
//				Toast.makeText(getActivity(), cmtEdt.getText(), 0).show();
//				
//				
//
//				 String urlPath = "http://ce.sejong.ac.kr/~firebat/uploads/";
//				
//				 List<String> permissions = session.getPermissions();
//				 if (!isSubsetOf(PERMISSIONS, permissions)) {
//				 pendingPublishReauthorization = true;
//				 Session.NewPermissionsRequest newPermissionsRequest = new
//				 Session.NewPermissionsRequest(
//				 getActivity(), PERMISSIONS);
//				 session.requestNewPublishPermissions(newPermissionsRequest);
//				 return;
//				 }
//				
//				 Bundle postParams = new Bundle();
//				 postParams.putString("name", name);
//				 postParams.putString("caption", mTime + mLoca);
//				 postParams.putString("description", "Test");
//				 postParams.putString("link",
//				 "https://developers.facebook.com/android");
//				 postParams.putString("picture", urlPath + id + ".png");
//				
//				 Request.Callback callback = new Request.Callback() {
//				 public void onCompleted(Response response) {
//				 JSONObject graphResponse = response.getGraphObject()
//				 .getInnerJSONObject();
//				 String postId = null;
//				 try {
//				 postId = graphResponse.getString("id");
//				 } catch (JSONException e) {
//				 Log.i("Callback JSON",
//				 "JSON error " + e.getMessage());
//				 }
//				 FacebookRequestError error = response.getError();
//				 if (error != null) {
//				 Toast.makeText(
//				 getActivity().getApplicationContext(),
//				 error.getErrorMessage(), Toast.LENGTH_SHORT)
//				 .show();
//				 } else {
//				 Toast.makeText(
//				 getActivity().getApplicationContext(),
//				 postId, Toast.LENGTH_LONG).show();
//				 }
//				 }
//				 };
//				 Request request = new Request(session, "me/feed", postParams,
//				 HttpMethod.POST, callback);
//				
//				 RequestAsyncTask task = new RequestAsyncTask(request);
//				 task.execute();
//				 //////////////////////////////////////
//			}
//		});
//		aDialog.setNegativeButton("취소", new DialogInterface.OnClickListener() {
//			public void onClick(DialogInterface dialog, int which) {
//				dialog.cancel();
//			}
//		});
//		AlertDialog ad = aDialog.create();
//		ad.show();

	}

	String[] getFriendList() {
		String path = Environment.getExternalStorageDirectory()
				+ "/E-Profile/user_information/user_log.txt";
		File dir = new File(path);
		BufferedReader br;
		String str;
		ArrayList<String> strArr = new ArrayList<String>();
		String[] strArr2;

		try {
			if (dir.exists())
				br = new BufferedReader(new FileReader(dir));
			else
				br = new BufferedReader(new FileReader(dir));

			while ((str = br.readLine()) != null) {
				while (!str.split("\t")[0].equals(MainActivity.user_id)) {
					strArr.add(str);
					break;
				}
			}
			br.close();
		} catch (FileNotFoundException e) {
			Log.d("filterDuplicate", e.toString());
		} catch (IOException e) {
			Log.d("filterDuplicate", e.toString());
		}

		strArr2 = new String[strArr.size()];
		strArr2 = strArr.toArray(strArr2);

		/*
		 * return 0 : no problem return 1 :
		 */

		return strArr2;
	}

	class BackThread extends Thread {
		public void run() {
			MOBILE_OS = getFriendList();

			mHandler.post(new Runnable() {
				public void run() {
					pBar.dismiss();
					setListAdapter(new SnsArrayAdapter(getActivity(), MOBILE_OS));
				}
			});
		} // run
	} //

	Handler mHandler = new Handler();

	private boolean isSubsetOf(Collection<String> subset,
			Collection<String> superset) {
		for (String string : subset) {
			if (!superset.contains(string)) {
				return false;
			}
		}
		return true;
	}

	private class SessionStatusCallback implements Session.StatusCallback {
		public void call(Session session, SessionState state,
				Exception exception) {
			// updateView();
		}
	}

}